//
//  StockVC.swift
//  SlaughterClient
//
//  Created by zwb on 2023/4/8.
//  Copyright © 2023 zwb. All rights reserved.
//

import UIKit

class ZyaStockVC: UIViewController {
    
    private var page = 1
    private lazy var searchBar = makeSearchBar()
    private lazy var tableView = makeTableView()
    private lazy var searchText = ""
    
    private var items = [ZyaStockItem]() {
        didSet {
            tableView.reloadData()
        }
    }
    // 可以查看
    private var allowed = false

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "动保库存"
         
        judgeIdentifier()
        makeUI()
        fetchData()
    }
    
}

extension ZyaStockVC {
    
    // 权限判断
    private func judgeIdentifier() {
        
        if isAuditAccount() {
            self.allowed = true
        } else {
            let arr = zyaequityArr.filter { $0.k_code == "dbkc" && $0.k_show_type == "1" }
            if arr.count > 0 {
                if meInfoM.member_type == "1" {
                    self.allowed = true
                } else {
                    self.allowed = false
                }
            } else {
                self.allowed = false
            }
        }
    }
 
    @objc
    private func fetchData() {
        searchBar.resignFirstResponder()
        searchText = searchBar.text.unwrap
        KSNetwork.shared.doRequest(.queryStock(page: page, title: searchText)) { [weak self] (result: BaseResult<ZyaStockItem>) in
            guard let `self` = self else { return }
            if result.flag == TRUE {
                if let infos = result.infos {
                    if self.page == 1 {
                        self.items.removeAll()
                    }
                    self.items += infos
                    self.tableView.mj_header?.endRefreshing()
                    if infos.count < KSGlobal.pageSize {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                }
            } else {
                KSToast(result.message)
            }
        }
    }
    
}

extension ZyaStockVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: ZyaStockCell.self, for: indexPath)
        if let item = items[safe: indexPath.item] {
            let unit = item.unit ?? ""
            var amount = item.amount.unwrap
            var number = item.number.unwrap
            if !allowed {
                amount = "***"
                number = "***"
            }
             cell.titleLabel.text = item.name
            cell.subtitleLabel.text = "库存: \(amount)\(unit)"
            cell.describeLabel.text = "近三个月使用: \(number)\(unit)"
        }
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return self.allowed ? 0 : 35
    }
     func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
         let headerView = tableView.dequeueReusableHeaderFooterView(withClass: ZyaStockHeader.self)
         headerView.actionBtn.addTouchUpInSideAction { _ in
             let vc = PurchaseMemberVC()
             self.navigationController?.pushViewController(vc, animated: true)
         }
         return headerView
        
        
    }
    
    
}

extension ZyaStockVC: UISearchBarDelegate {
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.searchText = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
    }
    
}

extension ZyaStockVC {
    
    private func makeUI() {
        if #available(iOS 13.0, *) {
            searchBar.searchTextField.backgroundColor = .white
            searchBar.searchTextField.layer.cornerRadius = 18
            searchBar.searchTextField.layer.masksToBounds = true
        } else {
            let searchField = searchBar.value(forKey: "searchField") as! UITextField
            searchField.backgroundColor = .white
            searchField.layer.cornerRadius = 18
            searchField.layer.masksToBounds = true
        }
        
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    private func makeTableView() -> UITableView {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 48))
        headerView.addSubview(searchBar)
        searchBar.snp.makeConstraints { make in
            make.width.centerY.centerX.equalToSuperview()
            make.height.equalTo(40)
        }
        return UITableView(frame: .zero, style: .plain).then {
            if #available(iOS 15.0, *) {
                $0.sectionHeaderTopPadding = 0
                    }
            $0.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
            $0.delegate = self
            $0.dataSource = self
            $0.separatorStyle = .none
            $0.estimatedRowHeight = 90
            $0.tableHeaderView = headerView
            $0.register(cellWithClass: ZyaStockCell.self)
            $0.register(headerFooterViewClassWith: ZyaStockHeader.self)
            $0.backgroundColor = UIColor(kshex: "#f3f3f3")
            $0.mj_header = KSRefreshHeader { [weak self] in
                self?.page = 1
                self?.fetchData()
            }
            $0.mj_footer = KSRefreshFooter { [weak self] in
                self?.page += 1
                self?.fetchData()
            }
        }
    }
    
    private func makeSearchBar() -> TenderSearchBar {
        return TenderSearchBar().then {
            $0.barTintColor = UIColor(kshex: "#f5f5f5")
            $0.backgroundImage = UIImage()
            $0.inputAccessoryView = self.makeToolbar()
            $0.text = self.searchText
            $0.placeholder = "请输入关键字"
            $0.delegate = self
        }
    }
    
    private func makeToolbar() -> UIToolbar {
        let barButtonItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let doneBtn = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(fetchData))
        doneBtn.tintColor = UIColor.black
        return UIToolbar().then {
            $0.barStyle = UIBarStyle.default
            $0.sizeToFit()
            $0.setItems([barButtonItem, doneBtn], animated: true)
        }
    }
    
}
